/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 IEndpointCoordinator.cpp. Created on: 09.06.2009 16:09:37
 */

#include "smartobjects/network/tcp/SocketMultiplexer.hpp"

namespace smartobjects {
	namespace sockets {

		SocketMultiplexer::SocketMultiplexer():
				m_poThread ( NULL ),
				m_bStopFlag(false),
				m_bHandlersRunStatus(false) {

			m_poThread = new boost::thread (
				boost::bind ( &SocketMultiplexer::run, this )
			);
		}

		SocketMultiplexer::~SocketMultiplexer() {
			m_bStopFlag = true;
			m_poThread->join();
			delete m_poThread;
			m_poThread = NULL;
		}

		void SocketMultiplexer::addSocketReader(Socket hSocket, ReaderHandler pfHandler, KeepAliveHandler pfKeepAliveHandler) {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			if (m_mReaderHandlers.size() >= FD_SETSIZE || m_mExceptHandlers.size() >= FD_SETSIZE )
				throw SystemException("Too many sockets handling per multiplexer");
			Handler poHandler;
			poHandler.setSocket (hSocket);
			poHandler.setReaderHandler ( pfHandler );
			poHandler.setKeepAliveHandler ( pfKeepAliveHandler );
			if ( !m_bHandlersRunStatus ) {
				m_mReaderHandlers [ hSocket ] = poHandler ;
				m_mExceptHandlers [ hSocket ] = poHandler ;
			}
			else {
				m_aPostProcessQueue.push_back ( poHandler );
			}
		}

		void SocketMultiplexer::removeSocketReader(Socket hSocket) {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			if ( !m_bHandlersRunStatus ) {
				m_mReaderHandlers.erase ( hSocket );
				m_mExceptHandlers.erase ( hSocket );
			}
			else {
				Handler poHandler;
				poHandler.setSocket (hSocket);
				poHandler.setReaderAction ( true );
				poHandler.setRemoved ( true );
				m_aPostProcessQueue.push_back ( poHandler );
			}
		}

		void SocketMultiplexer::addSocketAcceptor(Socket hSocket, AcceptorHandler pfHandler) {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			Handler poHandler;
			poHandler.setSocket (hSocket);
			poHandler.setAcceptorHandler ( pfHandler );
			if (m_mReaderHandlers.size() >= FD_SETSIZE)
				throw SystemException("Too many sockets handling per multiplexer");

			if ( !m_bHandlersRunStatus ) {
				m_mReaderHandlers [ hSocket ] = poHandler ;
			}
			else {
				m_aPostProcessQueue.push_back ( poHandler );
			}
		}

		void SocketMultiplexer::removeSocketAcceptor(Socket hSocket) {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			if ( !m_bHandlersRunStatus ) {
				m_mReaderHandlers.erase ( hSocket );
			}
			else {
				Handler poHandler;
				poHandler.setSocket (hSocket);
				poHandler.setAcceptorAction ( true );
				poHandler.setRemoved ( true );
				m_aPostProcessQueue.push_back ( poHandler );
			}
		}

		void SocketMultiplexer::addSocketConnector(Socket hSocket, ConnectorHandler pfHandler) {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			Handler poHandler;
			poHandler.setSocket (hSocket);
			poHandler.setConnectorHandler ( pfHandler );
			if (m_mWriterHandlers.size() >= FD_SETSIZE || m_mExceptHandlers.size() >= FD_SETSIZE)
				throw SystemException("Too many sockets handling per multiplexer");

			if ( !m_bHandlersRunStatus ) {
				m_mWriterHandlers [ hSocket ] = poHandler ;
				m_mExceptHandlers [ hSocket ] = poHandler ;
			}
			else {
				m_aPostProcessQueue.push_back ( poHandler );
			}
		}

		void SocketMultiplexer::removeSocketConnector(Socket hSocket) {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			if ( !m_bHandlersRunStatus ) {
				m_mWriterHandlers.erase ( hSocket );
				m_mExceptHandlers.erase ( hSocket );
			}
			else {
				Handler poHandler;
				poHandler.setSocket (hSocket);
				poHandler.setConnectorAction ( true );
				poHandler.setRemoved ( true );
				m_aPostProcessQueue.push_back ( poHandler );
			}
		}

		void SocketMultiplexer::run() {

			do {
				boost::recursive_mutex::scoped_lock oHandlersLock (m_mxHandlers);

				SocketSet oReadersFDSet;
				SocketSet oWritersFDSet;
				SocketSet oExceptsFDSet;

				createFDSet ( m_mReaderHandlers, oReadersFDSet );
				createFDSet ( m_mWriterHandlers, oWritersFDSet );
				createFDSet ( m_mExceptHandlers, oExceptsFDSet );

				SocketSet* pReaders = &oReadersFDSet;
				SocketSet* pWriters = &oWritersFDSet;
				SocketSet* pExcepts = &oExceptsFDSet;
				unsigned int nReadersCnt = m_mReaderHandlers.size();
				unsigned int nWritersCnt = m_mWriterHandlers.size();
				unsigned int nExceptsCnt = m_mExceptHandlers.size();


				Socket nHighestDescriptor = 0;
				if(!m_mReaderHandlers.empty()) {
					nHighestDescriptor = ((--m_mReaderHandlers.end())->first);
				}

				if(!m_mWriterHandlers.empty()) {
					nHighestDescriptor = std::max (nHighestDescriptor, ((--m_mWriterHandlers.end())->first) );
				}

				if(!m_mExceptHandlers.empty()) {
					nHighestDescriptor = std::max (nHighestDescriptor, ((--m_mExceptHandlers.end())->first) );
				}

				nHighestDescriptor++;
				oHandlersLock.unlock();

				if ( !m_bStopFlag ) {
					if ( nReadersCnt + nWritersCnt + nExceptsCnt == 0  ) {
						boost::this_thread::sleep(boost::posix_time::milliseconds(WAIT_EVENT_INTERVAL_MILLISEC));						
					}
					else {
						if( osimpl::waitEventOnSocketSet (
								nHighestDescriptor,
								pReaders, pWriters, pExcepts,
								WAIT_EVENT_INTERVAL_MILLISEC ) ) {
							
							boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
							m_bHandlersRunStatus = true;

							if ( pReaders ) {								
								processReaderHandlers ( *pReaders, *pExcepts );
							}
							if ( pWriters ) {
								processWriterHandlers ( *pWriters );
							}
							if ( pExcepts ) {
								processExceptHandlers ( *pExcepts );
							}

							m_bHandlersRunStatus = false;
							postProcessHandlersQueue();

							postProcessKeepAliveCycle();

						}
						else {							
							boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
							postProcessKeepAliveCycle();
						}
					}
				}
			}
			while(!m_bStopFlag);
		}

		void SocketMultiplexer::processReaderHandlers ( SocketSet& oReadersSet, SocketSet& oExceptsSet ) {
			for ( Handlers::iterator it = m_mReaderHandlers.begin(); it!= m_mReaderHandlers.end(); it++) {
				Socket hSocket = it->first;
				if ( hSocket!=-1 && FD_ISSET ( hSocket, &oReadersSet )) {
					if(it->second.hasReaderHandler()) {
						ReaderHandler pfHandler = it->second.getReaderHandler();
						pfHandler( (bool) FD_ISSET ( hSocket, &oExceptsSet ) );
					}
					else
					if(it->second.hasAcceptorHandler()) {
						AcceptorHandler pfHandler = it->second.getAcceptorHandler();
						pfHandler();
					}
				}
			}
		}

		void SocketMultiplexer::processWriterHandlers ( SocketSet& oWritersSet ) {
			for ( Handlers::iterator it = m_mWriterHandlers.begin(); it!= m_mWriterHandlers.end(); it++) {
				Socket hSocket = it->first;
				if ( hSocket!=-1 && FD_ISSET ( hSocket, &oWritersSet )) {
					if(it->second.hasConnectorHandler()) {
						ConnectorHandler pfHandler = it->second.getConnectorHandler();
						pfHandler( !osimpl::checkSocketError(hSocket) );
						removeSocketConnector ( hSocket );
					}
				}
			}
		}

		void SocketMultiplexer::processExceptHandlers ( SocketSet& oExceptsSet ) {
			for ( Handlers::iterator it = m_mExceptHandlers.begin(); it!= m_mExceptHandlers.end(); it++) {
				Socket hSocket = it->first;
				if ( hSocket!=-1 && FD_ISSET ( hSocket, &oExceptsSet )) {					
					if(it->second.hasConnectorHandler()) {
						ConnectorHandler pfHandler = it->second.getConnectorHandler();
						pfHandler( false );
						removeSocketConnector ( hSocket );
					}
				}
			}
		}

		void SocketMultiplexer::createFDSet (Handlers& oHandlers, SocketSet& oSocketSet ) {
			osimpl::clearSocketSet ( oSocketSet );
			for ( Handlers::iterator it = oHandlers.begin(); it!= oHandlers.end(); it++) {
				osimpl::insertIntoSocketSet ( it->first, oSocketSet );
			}
		}

		void SocketMultiplexer::postProcessHandlersQueue ( ) {
			for ( HandlerList::iterator it = m_aPostProcessQueue.begin();
					it != m_aPostProcessQueue.end(); it++ ) {
				if ( it->isReaderAction() ) {
					if( !it->isRemoved() ) {
						addSocketReader ( it->getSocket(), it->getReaderHandler(), it->getKeepAliveHandler() );
					}
					else {
						removeSocketReader ( it->getSocket() );
					}
				}
				else
				if ( it->isAcceptorAction() ) {
					if( !it->isRemoved() ) {
						addSocketAcceptor ( it->getSocket(), it->getAcceptorHandler() );
					}
					else {
						removeSocketAcceptor ( it->getSocket() );
					}
				}
				else
				if ( it->isConnectorAction() ) {
					if( !it->isRemoved() ) {
						addSocketConnector ( it->getSocket(), it->getConnectorHandler() );
					}
					else {
						removeSocketConnector ( it->getSocket() );
					}
				}

			}
			m_aPostProcessQueue.clear();
		}

		bool SocketMultiplexer::isFull() {
			boost::recursive_mutex::scoped_lock oHandlersLock ( m_mxHandlers );
			if ( m_mReaderHandlers.size() >= FD_SETSIZE
				|| m_mWriterHandlers.size() >= FD_SETSIZE
				|| m_mExceptHandlers.size() >= FD_SETSIZE )
				return true;
			else
				return false;
		}

		void SocketMultiplexer::postProcessKeepAliveCycle() {
			for ( Handlers::iterator it = m_mReaderHandlers.begin(); it!= m_mReaderHandlers.end(); it++) {
				Socket hSocket = it->first;
				if ( hSocket!=-1 && it->second.hasKeepAliveHandler()) {
					KeepAliveHandler pfHandler = it->second.getKeepAliveHandler();
					pfHandler();
				}
			}
		}
	}

}
